<template>
  <page-wrap :header-props="headerProps" :loading="pageloading">
    <template #extension>
      <div class="open-header">
        <div class="header-main">
          <div :class="[
            'header-main-item',
            v.class,
            tabActive == v.type ? 'active' : null
          ]" v-for="(v, k) in tabList" :key="k" @click="onState(v.type)">
            {{ v.name }}{{ k != 6 ? `(${v.num})` : null }}
          </div>
        </div>
        <div class="header-footer">
          <van-popover v-model:show="showPopover" :show-arrow="true" :actions="actions" class="popoverOne"
            :offset="[35, 8]" @select="onSelect" theme="dark">
            <template #reference>
              <div class="header-footer-select">
                <div class="header-footer-icon"></div>
                {{ sortText }}
              </div>
            </template>
          </van-popover>
          <z-search
            placeholder="请输入台号"
            @query="onQuery"
            @update:model-value="onUpdateVal"
        ></z-search>
        </div>
      </div>
    </template>
    <div class="open-container">
      <div class="open-main">
        <z-sidebar :current-active="menuActive" :menu-list="zoneList" @click="onZone" />
        <div class="main-right">
          <z-empty v-if="!tableList.length"></z-empty>
          <div class="right-main" ref="scrollContainer">
            <div class="card" v-for="(v, k) in tableList" :key="k" @click="onControlTable(v, k)" :class="getTypeClass(v.consumeState, k)">
              <div class="card-top">
                <div class="card-top-name" :class="{ lock: v.isLock == true, spe: v.state == 0 }">
                  {{ v.roomName }}
                </div>
                <div class="card-top-state spe" v-if="v.state == 0">维修中</div>
                <div class="card-top-state lock" v-if="v.isLock == true">
                  锁定中
                </div>
                <div class="card-top-state" v-if="v.state != 0 && v.isLock != true">  
                  {{ v.ConsumeStateName }}  
                </div>
              </div>
              <div class="card-main">
                <div class="card-main-item">
                  <div class="card-item-label">人数</div>
                  <div class="card-item-li" v-if="v.consumeState !== '1'">
                    {{
                      v.consumeState === '2' || v.consumeState === '3'
                      ? v.currentPeople
                      : v.maxPeople
                    }}人
                  </div>
                  <div class="card-item-li" v-if="v.consumeState === '1'">
                    {{ v.reservePeople }}人
                  </div>
                </div>
                <div class="card-main-item">
                  <div class="card-item-label">低消</div>
                  <div class="card-item-li" v-if="v.consumeState == 0">
                    ￥{{ v.minConsume }}
                  </div>
                  <div class="card-item-li" v-if="v.consumeState == 1">
                    ￥{{ v.reserveMinConsume }}
                  </div>
                  <div class="card-item-li" v-if="v.consumeState == 2 || v.consumeState == 3">
                    ￥{{ v.consumeMinConsume }}
                  </div>
                </div>
                <div class="card-main-item" v-if="v.consumeState == 3">
                  <div class="card-item-label">未付金额</div>
                  <div class="card-item-li" >
                    ￥{{ v.unPayAmt }}
                  </div>
                </div>
                <block v-if="ls.get('BRAND_CODE') && ls.get('BRAND_CODE') != '0003'">
                  <div class="card-main-item" v-if="v.consumeState == 2 || v.consumeState == 3">
                    <div class="card-item-label">实消</div>
                    <div class="card-item-li">￥{{ v.realAmt }}</div>
                  </div>
                </block>
                  
                
                <div class="card-main-item" v-if="v.all">
                  <div class="card-item-label">累充</div>
                  <div class="card-item-li">￥{{ v.all }}</div>
                </div>
                <div class="card-main-item" v-if="v.consumeState !== '1'">
                  <div class="card-item-label">开台时间</div>
                  <div class="card-item-li" v-if="v.consumeState == '0'">
                    -- --
                  </div>
                  <div class="card-item-li" v-else>
                    <div class="card-item-time">
                      {{ v.openTime ? dayjs(v.openTime).format('HH:mm') : '' }}
                    </div>
                  </div>
                </div>
                <div class="card-main-item" v-if="v.consumeState !== '1'">
                  <div class="card-item-label">开台时长</div>
                  <div class="card-item-li" v-if="v.consumeState == '0'">
                    -- --
                  </div>
                  <div class="card-item-li" v-else>
                    <div class="card-item-time">
                      {{
                        v.openTime
                        ? dayjs().diff(v.openTime, 'minute') + 'min'
                        : ''
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-main-item" v-if="v.consumeState == '1'">
                  <div class="card-item-label">到店时间</div>
                  <div class="card-item-li">
                    <div class="card-item-time">
                      {{
                        v.reserveTime
                        ? dayjs(v.reserveTime).format('HH:mm')
                        : ''
                      }}
                    </div>
                    <div class="card-item-date">
                      {{
                        v.reserveTime
                        ? dayjs(v.reserveTime).format('YYYY-MM-DD')
                        : ''
                      }}
                    </div>
                  </div>
                </div>
                <div class="card-main-item" v-if="v.consumeState == '1'" style="padding-top: 0px;">
                  <div class="card-item-label">预留时间</div>
                  <div class="card-item-li">
                    <div class="card-item-time">
                      {{v.keepTime? dayjs(v.reserveTime).add(30, 'minute').format('HH:mm') : '' }}
                    </div>
                    <div class="card-item-date">
                      {{v.keepTime? dayjs(v.reserveTime).add(30, 'minute').format('YYYY-MM-DD'): ''}}
                    </div>
                  </div>
                </div>
                <div class="card-main-item" v-if="v.consumeState == '2' || v.consumeState == '3'">
                  <div class="card-item-label">赠送</div>
                  <div class="card-item-li">￥{{ v.currentGive }}</div>
                </div>
              </div>
              <div class="card-content">
                <div class="card-content-item">
                  <div class="card-content-label">来源:</div>
                  <div class="card-item-li spe" v-if="v.reserveSourceType == '104004' || v.consumeSourceType == '104004'">
                    <span class="ly-spe" v-for="(part, index) in splitName(v.maintainUserName)" :key="index">
								        {{ part }}
								        <!-- 如果不是最后一部分，插入换行符 -->
								        <span v-if="index < splitName(v.maintainUserName).length - 1" class="line-break"></span>
                    </span>
                  </div>
                  <div class="card-item-li spe" v-else>
                    {{ v.consumeState == '1' ? v.reserveSourceTypeName : v.consumeSourceTypeName }}
                    
                    <!-- {{ 
                      // v.reserveSourceTypeName
                      // ? v.reserveSourceTypeName
                      // : '-- --'
                    }} -->
                  </div>
                </div> 
                <template v-if="v.consumeState !== 0">
                  <div class="card-content-item" v-if="v.consumeState == '1'">
                    <div class="card-content-label">客户:</div>
                    <div class="card-item-li">
                      {{
                        v.reserveMemberName && v.reserveMemberName.length > 6
                        ? v.reserveMemberName.substring(0, 6) + '..'
                        : v.reserveMemberName
                      }}
                    </div>
                  </div>
                  <div class="card-content-item" v-if="v.consumeState !== '1' && v.consumeMemberName">
                    <div class="card-content-label">客户:</div>
                    <div class="card-item-li">
                      {{
                        v.consumeMemberName.length > 6
                        ? v.consumeMemberName.substring(0, 6) + '..'
                        : v.consumeMemberName
                      }}
                    </div>
                  </div>
                </template>
              </div>
              <div class="card-footer" v-if="v.consumeState == '0'">
                备注：-- --
              </div>
              <div class="card-footer" v-if="v.consumeState == '1'" @click.stop="onNotes(v.reserveRemark)">
                备注：{{ v.reserveRemark || '-- --' }}
              </div>
              <div class="card-footer" v-if="v.consumeState == '2' || v.consumeState == '3'"
                @click.stop="onNotes(v.consumeRemark)">
                备注：{{ v.consumeRemark || '-- --' }}
              </div>
              <div class="card-lock" v-if="v.isLock == true"></div>
              <div class="card-turn" v-if="v.beforeRoomCode"></div>
              <div class="card-pre" v-if="v.consumeState == '1' && v.reserveConsumeCode" @click.stop="handlePre(v)" style="margin-top: 4px;">
                预点<van-icon name="arrow" />
              </div> 
            </div>
          </div>
        </div>
      </div>
    </div>
  </page-wrap>
  <!-- 磁吸控制台 -->
  <!-- <van-floating-bubble v-model:offset="bubLoc" axis="xy" magnetic="x" @click="onPanel" @offset-change="onOffsetChange">
    <van-popover class="open-bubble-popover" v-model:show="fastShow" :actions="fastActions" :placement="fastPosition"
      :offset="fastOffset" overlay :overlay-style="{
        background: 'transparent'
      }" @select="onSelectFast"></van-popover>
  </van-floating-bubble> -->
  <!-- 确认维修弹出框 -->
  <z-dialog v-model:show="confirmRepairShow" v-if="tableInfo.state == '0'" content="是否确认进行解除维修操作?"
    @confirm="onConfirmRepair"></z-dialog>
  <z-dialog v-model:show="confirmRepairShow" v-if="tableInfo.state != '0'" content="是否确认进行维修操作？"
    @confirm="onConfirmRepair"></z-dialog>
  <!-- 确认锁定弹出框 -->
  <z-dialog v-model:show="confirmLockShow" v-if="tableInfo.isLock" content="是否确认进行解锁操作?"
    @confirm="onConfirmLock"></z-dialog>
  <z-dialog v-model:show="confirmLockShow" v-if="!tableInfo.isLock" content="是否确认进行锁台操作？"
    @confirm="onConfirmLock"></z-dialog>
  <!-- 备注弹窗 -->
  <z-popup v-model:show="notes" closeable :style="{ width: '300px' }">
    <div class="popup-remark">
      <div class="popup-remark-title">备注</div>
      <div class="popup-remark-content">{{ notesContemt }}</div>
    </div>
  </z-popup>
  <!-- 取消预订弹窗 -->
  <z-popup v-model:show="cancelPre" closeable :style="{ width: '334px' }" title="取消预订">
    <div class="popup-cancel">
      <div class="cancelPre-main" @click="cancelShow = true">
        <div class="cancelPre-main-left">取消原因</div>
        <div class="cancelPre-main-right">
          <div class="cancelPre-right-icon"></div>
          {{ cancelReason }}
        </div>
      </div>
      <van-field v-model="cancelBookForm.remark" name="备注" label="备注" placeholder="请输入备注" autocomplete="off" />
      <z-button @click="onSubmitCancel" :style="{ width: '160px', margin: '30px auto 0' }">确定取消</z-button>
    </div>
  </z-popup>
  <!-- 底部弹窗 -->
  <z-popup v-model:show="panelShow" closeable position="bottom" @click="onJump" :title="titleNum"
    style="border-radius: 24px 24px 0px 0px">
    <div class="popup-panel">
      <template v-if="tableState == 2 || tableState == 3">
        <div class="popup-use">
          <div class="popup-use-main">
            <div class="use-main-left">
              <div class="main-item-records" v-has-role="'waiter-openRoom-operLog'" data-id="open/records">
                操作记录
              </div>
              <div class="main-item-certificate" v-has-role="'waiter-order-ticket-check'" data-id="open/certificate">
                核销券
              </div> 
              <div class="use-main-item" v-has-role="'waiter-order-transfer'" data-id="turnTable">转台</div>
              <div class="use-main-item" v-has-role="'waiter-order-clear'" data-id="clear">清台</div>
            </div>
            <div class="use-main-right">
              <div class="main-item-order"  data-id="open/order">点单</div>
            </div>
          </div>
          <div class="popup-use-footer">
            <div class="use-main-item-left" v-has-role="'waiter-order-detail'" data-id="open/table">详情</div>
            <div class="use-main-item-left" v-has-role="'waiter-order-edit'" data-id="open/confirm/edit">编辑</div>
            <div class="use-main-item-right spe" v-has-role="'waiter-checkout'" data-id="open/orderCashier">
              结账
            </div>
          </div>
        </div>
      </template>
      <template v-if="tableState == 0 && tableInfo.isLock != true && tableInfo.state != 0
        ">
        <div class="popup-idle">
          <div class="popup-idle-main">
            <div class="idle-main-left">
              <div class="main-left-item" v-has-role="'waiter-openRoom-operLog'" data-id="open/records">操作记录</div>
              <div class="main-left-item" v-has-role="'waiter-openRoom-repair'"  data-id="maintain">维修</div>
            </div>
            <div class="idle-main-right">
              <div class="main-right-item" v-has-role="'waiter-openRoom-reserve'" data-id="book/form">预订</div>
              <div class="main-right-item spe" v-has-role="'waiter-openRoom-lock'" data-id="lock">锁定/解锁</div>
            </div>
            <div class="idle-main-right">
              <div class="main-right-spe" v-has-role="'waiter-openRoom-open'" data-id="open/confirm">开台</div>
            </div>
          </div>
        </div>
      </template>
      <template v-if="tableState == 1">
        <div class="pre-main">
          <div class="pre-main-left">
            <div class="pre-main-records" v-has-role="'waiter-openRoom-operLog'" data-id="open/records">操作记录</div>
            <div class="pre-main-item" v-has-role="'waiter-order-transfer'" data-id="turnTable">转台</div>
            <div class="pre-main-item" v-has-role="'waiter-openRoom-reserveCancel'"  data-id="cancelBook">取消预订</div>
            <div class="pre-main-item" v-has-role="'waiter-order-edit'" data-id="book/form/edit">编辑</div>
          </div>
          <div class="pre-main-right">
            <div class="main-middle-right spe" v-has-role="'waiter-openRoom-open'" data-id="open/confirm">开台</div>
          </div>
        </div>
      </template>
      <template v-if="tableInfo.isLock == true">
        <div class="pre-main">
          <div class="pre-main-left">
            <div class="pre-main-records" v-has-role="'waiter-openRoom-lock'" data-id="lock">锁定/解锁</div>
            <!-- <div class="pre-main-item" data-id="turnTable">转台</div>
                        <div class="pre-main-item" data-id="cancelBook">取消预订</div>
                        <div class="pre-main-item" data-id="book/form/edit">编辑</div> -->
          </div>
          <!-- <div class="pre-main-right">
                        <div class="main-middle-right spe" data-id="open/confirm">开台</div>
                    </div> -->
        </div>
      </template>
      <template v-if="tableInfo.state == 0">
        <div class="pre-main">
          <div class="pre-main-left">
            <div class="pre-main-records" v-has-role="'waiter-openRoom-repair'" data-id="maintain">维修</div>
            <!-- <div class="pre-main-item" data-id="turnTable">转台</div>
                        <div class="pre-main-item" data-id="cancelBook">取消预订</div>
                        <div class="pre-main-item" data-id="book/form/edit">编辑</div> -->
          </div>
          <!-- <div class="pre-main-right">
                        <div class="main-middle-right spe" data-id="open/confirm">开台</div>
                    </div> -->
        </div>
      </template>
    </div>
  </z-popup>
  <!-- 选择桌台组件 -->
  <!-- 并台、转台 -->
  <TableSelect v-model:show="tableSelectShow" @close="onTableSelectClose" :title="tableTitle" :source="tableSource"
    :state="tableRoomState" :tableCode="postForm.roomCode" :tableConsumeCode="postForm.consumeCode"
    :tableName="postForm.roomName" :reserveCode="postForm.reserveCode" :currentPeople="currentPeople"></TableSelect>
  <!-- 取消原因选择器 -->
  <z-picker v-model:show="cancelShow" :columns="cancelColumns" title="取消原因" @confirm="onConfirmCancel" />
  <!-- 清台确认框 -->
  <z-dialog v-model:show="clearShow" title="清台" content="确认是否清台" @confirm="onConfirmClear"></z-dialog>
</template>
<script setup>
import dayjs from 'dayjs'
import useAppStore from '@/store/app'
import useConfigStore from '@/store/config'
import { showToast } from 'vant'
import { transformArrayProps } from '@/lib/util.js'
import Api from '@/api'
import useCartStore from '@/store/cart'
import ls from '@/lib/ls'
import _ from 'lodash'



import i_white_notice from '@/assets/images/common/i_white_notice.png'
import { nextTick, ref } from 'vue'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const configStore = useConfigStore()
const cartStore = useCartStore()
const sourceData = ref({})
const zoneActive = ref(0)
const zoneList = ref([])
const tableList = ref([])
const menuActive = ref(0)
const confirmRepairShow = ref(false)
const confirmLockShow = ref(false)
const clearShow = ref(false)

const splitName = (name) => {
  // console.log(name);
  if(!name){
    return ''
  }
  // 检查字符串是否包含 '-'
  if (name.includes('-')) {
    // console.log(name.split('-'));
    
    return name.split('-');  // 如果包含 '-', 执行分割
  }
  return [name];  // 如果不包含 '-', 返回原始字符串作为数组
};
const searchTableValue = ref('')
// 房台查询
const onQuery = val => {
  searchTable(val)
  searchTableValue.value = val
  // postForm.key = val
  // loadData(true)
}
const searchTimer = ref(null)
const toolTableList = ref([])
const searchTable = (val)=>{
  console.log(val);
  
  const list = toolTableList.value 
  const type = unref(zoneActive)
  let matchedRooms = list.filter(room => room.roomName.toLowerCase().includes(val.toLowerCase()));
  tableList.value = matchedRooms


  if(ls.get('ZONG') && ls.get('ZONG').menuActive){
    zoneActive.value = ls.get('ZONG').zoneActive
    menuActive.value = ls.get('ZONG').menuActive
    tableList.value = matchedRooms.filter(
          v => v.roomAreaCode == type && v.roomAreaCode == unref(zoneActive)
        )
  }else{
    zoneActive.value = '0'
    menuActive.value = 0
    tableList.value = matchedRooms
  }

  if(ls.get('ACTION') && ls.get('ACTION').id){
    let action = ls.get('ACTION')
    sortType.value = action.id
    sortText.value = action.text
  }
  if(sortText.value == '实消从低到高'){
    // 从小到大
    tableList.value = tableList.value.sort((a, b) => a.realAmt - b.realAmt);
  }
  if(sortText.value == '实消从高到低'){
    tableList.value = tableList.value.sort((a, b) => b.realAmt - a.realAmt);
  }
  
  
}
const onUpdateVal = val => {
  clearTimeout(unref(searchTimer))
  searchTimer.value = setTimeout(() => {
    searchTableValue.value = val
    searchTable(val)
  }, 500)
}
// 头部配置
const headerProps = {
  title: appStore.user_info.orgName,
  operation: [
    {
      type: 'icon',
      v: {
        backgroundImage: `url(${i_white_notice})`,
        backgroundSize: '20px auto'
      },
      click() {
        router.push('/notice')
      }
    }
  ],
  backFn: () => {
    router.push({
      path: '/'
    })
  }
}

// 头部选项卡
const tabActive = ref(appStore.tabActive)
watch(tabActive, nVal => {
  tableIndex.value = undefined
  const list = unref(allTableList)
  const type = unref(zoneActive)
  // 点击全部
  if (nVal == '100') {
    tableList.value =
      type == '0' ? list : list.filter(v => v.roomAreaCode == type)
    // 点击其他状态
  } else {
    console.log(nVal)
    let newArr = []
    switch (nVal) {
      case '4': // 维修
        newArr = list.filter(v => v.state == 0)
        break
      case '5': // 锁定
        newArr = list.filter(v => v.isLock == true)
        break
      default:
        newArr = list.filter(
          v => v.consumeState == nVal && v.state != 0 && v.isLock != true
        )
        break
    }

    tableList.value =
      type == '0'
        ? newArr
        : newArr.filter(
          v => v.roomAreaCode == type && v.roomAreaCode == unref(zoneActive)
        )
  }
  toolTableList.value = tableList.value
  sortFunc(unref(sortType))
  scrollToTop()
})

// 回到顶部的方法
const scrollContainer = ref(null)
const scrollToTop = () => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollIntoView({
      top: 0,
      behavior: 'auto'
    })
  }
}

// 确认维修
const onConfirmRepair = () => {
  let state = ''
  if (tableInfo.value.state == '0') {
    state = 1
  } else {
    state = 0
  }
  const roomRepair = Api.Common.AppObjProcess.Do({
    functionName: 'roomRepair',
    contentData: { roomList: tableInfo.value.roomCode, state: state }
  })
    .then(res => {
      getTableList()
      showToast('操作成功')
      confirmRepairShow.value = false
      panelShow.value = false
    })
    .catch(err => { })
}
const lockForm = ref({
  roomList: '', // 房台列表
  state: '', // 1 设置锁定 0 设置解锁
  currentDate: '', // 当前时间
  isLock: ''
})
// 确认锁台
const onConfirmLock = () => {
  lockForm.value.currentDate = dayjs().format('YYYY-MM-DD HH:mm:ss')

  if (lockForm.value.isLock) {
    lockForm.value.state = 0
  } else {
    lockForm.value.state = 1
  }
  // console.log(lockForm.value);
  Api.Common.AppObjProcess.Do({
    functionName: 'RoomLock',
    contentData: lockForm.value
  }).then(res => {
    confirmLockShow.value = false
    panelShow.value = false
    getTableList()
    showToast('操作成功')
  })
}
// 选择桌台
const tableTitle = ref('') // 选择桌台的标题
const tableSource = ref('') // 选择桌台的来源
const tableRoomState = ref('0') // 选择桌台的桌台状态
const tableNumber = ref(undefined)
//表单
const postForm = reactive({
  roomCode: '',
  roomName: '',
  consumeCode: '',
  reserveCode: ''
})
const tableSelectShow = ref(false) // 并台、转台弹窗
const onTableSelectClose = (type, args) => {
  if (type == 'success') {
    tableSelectShow.value = false
    panelShow.value = false
    getTableList()
    return
  }

  tableSelectShow.value = false

  if (type == 'back') return
  const { roomName, roomCode } = args
  // console.log(args);
  if (roomName) {
    tableNumber.value = args.roomName
    postForm.roomCode = args.roomCode
  }
}

// 选项卡
const tabList = ref([
  {
    name: '空闲',
    subname: '空闲中',
    type: '0',
    class: 'header-main-idle',
    num: ''
  },
  {
    name: '使用',
    subname: '使用中',
    type: '2',
    class: 'header-main-use',
    num: ''
  },
  {
    name: '预订',
    subname: '已预订',
    type: '1',
    class: 'header-main-pre',
    num: ''
  },
  {
    name: '未支付',
    subname: '未支付',
    type: '3',
    class: 'header-main-unpaid',
    num: ''
  },
  {
    name: '维修中',
    subname: '维修中',
    type: '4',
    class: 'header-main-repair',
    num: ''
  },
  {
    name: '锁定中',
    subname: '锁定中',
    type: '5',
    class: 'header-main-lock',
    num: ''
  },
  {
    name: '全部',
    subname: '全部',
    type: '100',
    class: 'header-main-all',
    num: ''
  }
])

// 监听所有桌台
const allTableList = ref([])
watch(
  allTableList,
  nVal => {
    let countMap = {
      0: 0,
      1: 0,
      2: 0,
      3: 0,
      4: 0,
      5: 0,
      ['100']: 0
    }
    nVal.forEach(item => {
      if (['0', '1', '2', '3'].includes(item.consumeState)) {
        if (item.state == 0 || item.isLock == true) {
        } else {
          countMap[item.consumeState]++
          countMap['100']++
        }
      }
      if (item.state == 0) {
        countMap[4]++
      }
      if (item.isLock == true) {
        countMap[5]++
      }
    })
    unref(tabList).forEach(item => {
      item.num = countMap[item.type].toString()
    })
  },
  { deep: true }
)

// 房态状态class
const getTypeClass = (state, index) => {
  return {
    cardActive: unref(tableIndex) == index,
    free: state == 0,
    book: state == 1,
    use: state == 2,
    unpay: state == 3
  }
}
// -------------------------------------头部筛选------------------------------------------------

const onState = type => {
  
  getTableList()
  console.log(tableList.value)
  tabActive.value = type
  appStore.tabActive = type
  console.log(appStore.tabActive)
  menuActive.value = 0
  nextTick(() => {
    configStore.curTable = tableList.value
    console.log(configStore.curTable)
  })
}

// -------------------------------------头部排序------------------------------------------------
const oldAllData = ref([])
const sortType = ref(0)
const sortText = ref('默认排序')
const showPopover = ref(false)
watch(sortType, nVal => {
  sortFunc(nVal)
})
const sortFunc = nVal => {
  // console.log(tableList.value);
  
  switch (nVal) {
    case 0:
      unref(tableList).sort((a, b) => a.sortNum - b.sortNum)
      break
    case 1:
      unref(tableList).sort((a, b) => b.currentConsume - a.currentConsume)
      break
    case 2:
      unref(tableList).sort((a, b) => a.currentConsume - b.currentConsume)
      break
  }
  searchTable(searchTableValue.value)
  scrollToTop()
}
// 通过 actions 属性来定义菜单选项
const actions = [
  { id: 0, text: '默认排序' },
  { id: 1, text: '实消从高到低' },
  { id: 2, text: '实消从低到高' }
]

const onSelect = action => {
  sortType.value = action.id
  sortText.value = action.text
  ls.set('ACTION',action)
}

//  ------------------------------------ 卡片 -----------------------------------------------------
const tableIndex = ref() // 当前选中卡片索引
const tableInfo = ref({})
const tableState = ref({})
const onControlTable = (item, index) => {
  tableInfo.value = item
  tableIndex.value = index
  tableState.value = item.consumeState
  titleNum.value = item.roomName
  panelShow.value = true
}
const notes = ref(false) // 备注弹窗
const notesContemt = ref('')
const onNotes = val => {
  if (!val) return
  notes.value = !notes.value
  notesContemt.value = val
}

//  ------------------------------------ 弹出层 -------------------------------------------------
const pageloading = ref(false)
const panelShow = ref(false)
const titleNum = ref('')
const currentPeople = ref('')
const onJump = async(e) => {
  const id = e.target.dataset.id
  const d = unref(tableInfo)
  console.log('tableInfo :>> ', tableInfo);
  const openData = {
    // 预订页
    roomCode: '',
    roomName: '',
    typeCode: '',
    minConsume: '',
    // 开台页
    reserveCode: '',
    // 常量
    consumeState: '',
    source: 'open',
    consumeCode: '',
  }
  for (const key in d) {
    if (openData.hasOwnProperty(key)) {
      openData[key] = d[key]
    }
  }
  // return
  switch (id) {
    // 转台
    case 'turnTable':
      tableTitle.value = '转台' // 选择桌台的标题
      tableSource.value = 'turnTable' // 选择桌台的来源
      tableRoomState.value = '0' // 选择桌台的桌台状态
      tableSelectShow.value = true
      postForm.roomCode = d.roomCode
      postForm.roomName = d.roomName
      postForm.consumeCode = d.consumeCode
      postForm.reserveCode = d.reserveCode
      break
    // 并台
    case 'mergeTable':
      if (d.consumeState == 3) {
        showToast('订单未支付，不支持并台操作')
        return
      }
      tableTitle.value = '并台' // 选择桌台的标题
      tableSource.value = 'mergeTable' // 选择桌台的来源
      tableRoomState.value = '2' // 选择桌台的桌台状态
      tableSelectShow.value = true
      postForm.roomCode = d.roomCode
      postForm.roomName = d.roomName
      postForm.consumeCode = d.consumeCode
      currentPeople.value = d.currentPeople // 当前桌台人数
      // console.log(postForm);
      break
    // 取消预订
    case 'cancelBook':
      cancelPre.value = true
      break
    case 'clear':
      if (d.consumeState == 3) {
        showToast('订单未支付，不支持清台操作')
        return
      }
      clearShow.value = true
      ls.remove('PAY_TYPE')
      ls.remove('ORDER_BATCH_CODE')
      ls.remove('ORDER_FORM')
      break
    // 维修
    case 'maintain':
      console.log(tableInfo.value.state)
      console.log(tableInfo.value.state == '0')
      confirmRepairShow.value = true
      break
    // 修改预订信息
    case 'book/form/edit':
      router.push({
        path: `/book/form`,
        query: {
          ...openData,
          source: 'edit',
          typeName: d.typeName
        }
      })
      break
    // 修改开台信息
    case 'open/confirm/edit':
      router.push({
        path: `open/confirm`,
        query: {
          ...openData,
          source: 'edit',
          typeName: d.typeName,
          consumeCode: d.consumeCode
        }
      })
      break
    // 下单
    case 'open/order':
      cartStore.payAmt = 0
      cartStore.realPayAmt = 0
      cartStore.totalOrderAmt = 0
      cartStore.giveChange = 0
      cartStore.smallChange = 0
      ls.remove('CART_LIST')
      ls.remove('ORDER_INFO')  // 去除（先买单的下单标记）
      cartStore.cartList = []
      cartStore.tableInfo = {
        roomName: d.roomName,
        roomCode: d.roomCode,
        waiterUserCode: appStore.user_info.userCode,
        waiterUserName: appStore.user_info.userName,
        minConsume: d.minConsume,
        consumeCode: d.consumeCode,
        currentConsume: d.currentConsume,
        consumeMinConsume: d.consumeMinConsume,
        consumeRemark: d.consumeRemark
      }
      ls.set('ORDER_BATCH_CODE', d.orderBatchCode)
      ls.set('TABLE_INFO', cartStore.tableInfo)
      if (d.payBatchCode == '' || !d.payBatchCode) {
        router.push({
          path: `/${id}`
        })
      } else {
        cartStore.orderBatchCode = d.orderBatchCode
        cartStore.payBatchCode = d.payBatchCode

        ls.set('PAY_BATCH_CODE', d.payBatchCode)
        ls.remove('PAY_TYPE')
        router.push({
          path: `/open/orderCashier`
        })
      }

      // 是否有未支付订单
      // if (d.orderBatchCode == '' || d.orderBatchCode == null) {
      //     router.push({
      //         path: `/${id}`
      //     })
      // } else {
      //     cartStore.orderBatchCode = d.orderBatchCode
      //     cartStore.payBatchCode = d.payBatchCode
      //     ls.set('ORDER_BATCH_CODE', d.orderBatchCode)
      //     ls.set('PAY_BATCH_CODE', d.payBatchCode)
      //     router.push({
      //         path: `/open/orderCashier`
      //     })
      // }
      break
    // 结账
    case 'open/orderCashier':
      console.log(d)
      if (d.consumeState != '3') {
        showToast('没有未支付的订单')
        return
      }
      ls.remove('CART_LIST')
      ls.remove('ORDER_INFO')  // 去除（先买单的下单标记）
      cartStore.cartList = []
      cartStore.tableInfo = {
        roomName: d.roomName,
        roomCode: d.roomCode,
        waiterUserCode: appStore.user_info.userCode,
        waiterUserName: appStore.user_info.userName,
        minConsume: d.minConsume,
        consumeCode: d.consumeCode,
        currentConsume: d.currentConsume,
        consumeMinConsume: d.consumeMinConsume,
        consumeRemark: d.consumeRemark
      }
      ls.set('TABLE_INFO', cartStore.tableInfo)
      cartStore.orderBatchCode = d.orderBatchCode
      cartStore.payBatchCode = d.payBatchCode
      ls.set('ORDER_BATCH_CODE', d.orderBatchCode)
      ls.set('PAY_BATCH_CODE', d.payBatchCode)
      if(ls.get('ORG_CODE') == '0024' || ls.get('ORG_CODE') == '0025'){
        pageloading.value = true
        // 锁台操作
        await Api.Common.AppObjProcess.Do({ "functionName": "LockConsumeCode", "contentData": {consumeCode:d.consumeCode} })
          .then(res => {
              // 没有支付中的订单
              console.log(res);
              
              if (!d.payBatchCode) {
                router.push({
                  path: `/open/orderConfirm`,
                  query: { from: 'open' }
                })
              } else {
                // 有支付中的订单
                router.push({
                  path: '/open/orderCashier'
                })
                ls.set('PAY_TYPE', 3)
              }
              pageloading.value = false
          })
          .catch(err=>{
            // showToast('有服务员在结账中，请稍等')
            pageloading.value = false
          })
      }else{
         
        if (!d.payBatchCode) {
                router.push({
                  path: `/open/orderConfirm`,
                  query: { from: 'open' }
                })
              } else {
                // 有支付中的订单
                router.push({
                  path: '/open/orderCashier'
                })
                ls.set('PAY_TYPE', 3)
              }
      }
     
     
      break
    // 详情
    case 'open/table':
      // console.log(d,'table----')
      // return
      router.push({
        path: `/${id}`,
        query: {
          roomName: d.roomName,
          roomCode: d.roomCode,
          consumeCode: d.consumeCode,
          openTime:dayjs(d.openTime).format('YYYY-MM-DD HH:mm:ss'),
          maintainUserName:d.maintainUserName
        }
      })
      ls.set('ROOM_DETAIL', d)
      break
    case 'lock':
      confirmLockShow.value = true
      lockForm.value.roomList = d.roomCode
      lockForm.value.isLock = d.isLock
      break
    // 默认跳转
    default:
      if (id == 'open/confirm' || 'book/form') {
        cartStore.payAmt = 0
        cartStore.realPayAmt = 0
        cartStore.totalOrderAmt = 0
        cartStore.giveChange = 0
        cartStore.smallChange = 0
        openData.typeName = d.typeName
      }
      if (id) {
        router.push({
          path: `/${id}`,
          query: {
            ...openData
          }
        })
      }
  }
}
//----------------------------------------取消预订----------------------------------------------
const cancelPre = ref(false)
const cancelReason = ref('请选择')
const cancelShow = ref(false)
const cancelColumns = ref([])

const cancelBookForm = reactive({
  roomCode: '',
  reserveCode: '',
  cancelReason: undefined,
  remark: ''
})

// 选择取消原因
const onConfirmCancel = e => {
  cancelReason.value = e.selectedOptions[0].text
  cancelBookForm.cancelReason = e.selectedOptions[0].text
  cancelShow.value = false
}

// 确认取消
const onSubmitCancel = () => {
  if (!cancelBookForm.cancelReason) {
    showToast('请选择取消原因')
    return
  }
  cancelBookForm.roomCode = unref(tableInfo).roomCode
  cancelBookForm.reserveCode = unref(tableInfo).reserveCode
  Api.Common.AppObjProcess.Do({
    functionName: 'reserveCancel',
    contentData: cancelBookForm
  }).then(res => {
    showToast('取消成功')
    cancelPre.value = false
    cancelReason.value = '请选择'
    cancelBookForm.cancelReason = undefined
    panelShow.value = false
    getTableList()
  })
}

// 磁吸控制台
const fastShow = ref(false)
const fastActions = [
  { text: '商品管理', name: 'onproduct' },
  { text: '会员管理', name: 'onmember' },
  { text: '销售排行', name: 'rank' },
  { text: '营业统计', name: 'statistics' },
  { text: '收银汇总', name: 'collect' }
]
const onPanel = function (e) {
  fastShow.value = true
}
const bubLoc = reactive({
  x: appStore.bubblePosition.x || undefined,
  y: appStore.bubblePosition.y || undefined
})
const onOffsetChange = offset => {
  bubLoc.x = offset.x.toFixed(0)
  bubLoc.y = offset.y.toFixed(0)
  appStore.SetBubblePosition(offset)
}
const fastOffset = ref([22, 40])
const fastPosition = computed(() => {
  const sW = window.innerWidth / 2
  const sH = window.innerHeight / 2
  if (bubLoc.x !== undefined && bubLoc.y !== undefined) {
    if (bubLoc.x <= sW && bubLoc.y <= sH) {
      fastOffset.value = [-22, 40]
      return 'bottom-start'
    } else if (bubLoc.x > sW && bubLoc.y <= sH) {
      fastOffset.value = [22, 40]
      return 'bottom-end'
    } else if (bubLoc.x > sW && bubLoc.y > sH) {
      fastOffset.value = [22, 40]
      return 'top-end'
    } else if (bubLoc.x <= sW && bubLoc.y > sH) {
      fastOffset.value = [-22, 40]
      return 'top-start'
    }
  }
  return 'top-end'
})
const onSelectFast = function (action, index) {
  router.push({
    path: `/${action.name}`
  })
}

// 监听sidebar切换
watch(zoneActive, nVal => {
  tableIndex.value = undefined
  const list = unref(allTableList)
  const type = unref(tabActive)
  if (nVal == '0') {
    tableList.value =
      type == '100' ? list : list.filter(v => v.consumeState == type)
  } else {
    const newArr = list.filter(
      v => v.roomAreaCode == nVal && v.roomAreaCode == unref(zoneActive)
    )
    console.log(newArr);
    
    tableList.value =
      type == '100' ? newArr : newArr.filter(v => v.consumeState == type)
  }
  toolTableList.value = tableList.value
  sortFunc(unref(sortType))
  scrollToTop()
})
// 点击sidebar的回调
const onZone = (code, k) => {
  console.log(code, k);
  
  zoneActive.value = code
  menuActive.value = k
  ls.set('ZONG',{
    zoneActive:zoneActive.value,
    menuActive:menuActive.value
  })
}

// 获取桌台列表
const getTableList = async () => {
  const resp = await Api.Common.AppObjProcess.Do({
    functionName: 'getRoomInfoNew',
    contentData: ''
  })
  const output = resp.result.map((obj, index) => ({ ...obj, sortNum: obj.index }))
  console.log(output)
  console.log(tabActive.value)
  if (tabActive.value == 4) {
    tableList.value = output.filter(v => v.state == 0)
  } else if (tabActive.value == 5) {
    tableList.value = output.filter(v => v.isLock == true)
  } else if (tabActive.value == 100){ 
    tableList.value = output.filter( v =>v.consumeState )
  } else {
    tableList.value = output.filter(
      v =>
        v.consumeState == unref(tabActive) && v.state != 0 && v.isLock != true
    )
  }
  toolTableList.value = tableList.value
  console.log(tableList.value)
  configStore.curTable = tableList.value
  console.log(configStore.curTable)
  allTableList.value = output
  searchTable(searchTableValue.value)
}

// 确认清台
const onConfirmClear = () => {
  const roomCode = unref(tableInfo).roomCode
  Api.Common.AppObjProcess.Do({
    functionName: 'roomClear',
    contentData: roomCode
  }).then(res => {
    showToast('清台成功')
    clearShow.value = false
    panelShow.value = false
    getTableList()
  })
}


// 初始化
const onInit = async () => {
  const transArea = [
    ['roomAreaName', 'name'],
    ['roomAreaCode', 'code']
  ]
  const transCancel = [
    ['name', 'text'],
    ['code', 'value']
  ]
  zoneList.value = transformArrayProps(configStore.zoneList, transArea)
  zoneList.value.sort((a, b) => b.orderIndex - a.orderIndex);
  cancelColumns.value = transformArrayProps(configStore.cancelList, transCancel)
  zoneList.value.unshift({ name: '全部', code: '0' })
  sourceData.value = configStore.sourceList.reduce(
    (obj, { code, name }) => ({ ...obj, [code]: name }),
    {}
  )
  getTableList()
  
  // console.log('走两次？')
  // 0空闲 1预订 2使用 3未支付
  // console.log(zoneList.value)
}
onInit()

const visibilityFlag = ref(false)
const handleVisibilityChange = () => {
      if (document.hidden) {
        if(!visibilityFlag.value){
          visibilityFlag.value = true
          getTableList()
          setTimeout(() => {
            visibilityFlag.value = false
          }, 10000);
        }
        
      } 
    };
onMounted(() => {
  document.addEventListener('visibilitychange', handleVisibilityChange);
});

onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange);
});

// 点击预点
const handlePre = (item) => {
  console.log('v :>> ', item);
  router.push({
    path: `/open/pre`,
    query: { "consumeCode": item.reserveConsumeCode }
  })
} 
</script>
<style scoped lang="scss">
@import './style.scss';
</style>
